package com.siro.pm.utils;

import java.io.File;
import java.io.FileInputStream;

import com.vaadin.Application;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.FileResource;
import com.vaadin.terminal.Terminal.ErrorEvent;

/**
 * Class Declaration:
 * 
 * @version v1.0
 * @since FileDownloadResource.java v1.0
 */
public class FileDownloadResource extends FileResource {
	private static final long serialVersionUID = 4533290369931852819L;

	public FileDownloadResource(File sourceFile, Application application) {
		super(sourceFile, application);
	}

	public DownloadStream getStream() {
		try {
			final DownloadStream ds = new DownloadStream(new FileInputStream(
					getSourceFile()), getMIMEType(), getFilename());
			ds.setParameter("Content-Length",
					String.valueOf(getSourceFile().length()));
			String fileName = new String(getFilename().getBytes(), "ISO8859-1");
			ds.setParameter("Content-Disposition", "attachment; filename="
					+ fileName);
			ds.setCacheTime(getCacheTime());
			return ds;
		} catch (final Exception e) {
			// Log the exception using the application error handler
			getApplication().getErrorHandler().terminalError(new ErrorEvent() {
				private static final long serialVersionUID = -2399088068597853042L;

				public Throwable getThrowable() {
					return e;
				}

			});

			return null;
		}
	}
}
